package com.htudata.item.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;

import com.htudata.common.service.TokenService;
import com.htudata.item.dao.ItemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ItemCUDService {

  @Autowired
  private ItemDao itemDao;
  
  @Autowired
  private HttpServletRequest request;
  
  public Object showOrHideItems(String nodeId, int isShowed, String a2) throws Exception {
    long userId = TokenService.getUserId(this.request);
    JSONObject data = new JSONObject();
    int result = 0;
    try {
      if (isShowed == 0) {
        this.itemDao.insertHidedItemNode(nodeId, userId);
      } else {
        this.itemDao.deleteHidedItemNode(nodeId, userId);
      } 
      result = 1;
      data.put("result", Integer.valueOf(result));
      data.put("nodeId", nodeId);
      return data;
    } catch (Exception e) {
      throw e;
    } 
  }
  
  public Map<String, Object> postItems(JSONObject params, String a2)throws Exception  {
    long userId = TokenService.getUserId(this.request);
    Map<String, Object> resultData = new HashMap<>();
    int result = 0;
    if (params.containsKey("flowId")) {

      String flowId = params.getString("flowId");
      List<Long> itemIds = Arrays.asList(params.getObject("itemIds", Long[].class));
      this.itemDao.deleteFlowHiddenItemsByFlowId(flowId, userId);
      if (!Objects.isNull(itemIds) && itemIds.size() > 0)
        this.itemDao.batchInsertFlowHiddenItems(flowId, itemIds, userId); 
      result = 1;
    } else if (params.containsKey("nodeId")) {
      String nodeId = params.getString("nodeId");
      List<Long> itemIds = Arrays.asList(params.getObject("itemIds", Long[].class));
      this.itemDao.deleteNodeShowedItemsByNodeId(nodeId, userId);
      if (!Objects.isNull(itemIds) && itemIds.size() > 0)
        this.itemDao.batchInsertNodeShowedItems(nodeId, itemIds, userId); 
      result = 1;
    } 
    resultData.put("result", Integer.valueOf(result));
    return resultData;
  }
  
  public Map<String, Object> parseJSONArrayToMap(JSONArray jsonArray) {
    Map<String, Object> map = new HashMap<>();
    jsonArray.forEach(object -> {
          JSONObject jsonObject = (JSONObject)object;
          if (jsonObject.containsKey("flow_id")) {
            map.put(jsonObject.getString("item_id"), jsonObject.get("flow_id"));
          } else if (jsonObject.containsKey("node_id")) {
            map.put(jsonObject.getString("item_id"), jsonObject.get("node_id"));
          } 
        });
    return map;
  }
}
